import React, { useState, useImperativeHandle, useEffect } from 'react';
import { Form, Input, Button, Modal, message ,Select} from 'antd';
import request from '../../utils/request';

export default function EditUser(props) {
  const { Option } = Select;
  const [isModalVisible, setIsModalVisible] = useState(false);
  // const [userID, setUserID] = useState('')
  const [form] = Form.useForm();
  const [userID,setUserID] = useState(0)

  //用useImperativeHandle暴露一些外部ref能访问的属性
  useImperativeHandle(props.onRef, () => {
    return {
      setIsModalVisible,
      // setUserID,
      getUser
    };
  });

  useEffect(()=>{
  },[])

  //获取用户信息
  async function getUser(userName){
    const {data} = await request.get(`/v1/user?username=${userName}`)
    console.log(data);
    const {ID,username,role} = data
    setUserID(ID)
    const str = role+''
    form.setFieldsValue({
      username,
      role:str
    });

  }

  // 提交添加用户表单成功
  const onFinish = async (values) => {
    console.log('Success:', values);
    let { username ,role} = values
    const password = ''
    role = parseInt(role)

    const data = await request.put(`/v1/user/${userID}`, { username, password, role })
    console.log(data);
    if (data.status === 200) {
      message.success('修改用户成功');
      setIsModalVisible(false);
      props.getUsers()
    }
    else {
      message.error(data.message);
    }
  };
  // 提交添加用户表单失败
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  //关闭对话框
  function closeModal(){
      setIsModalVisible(false);
  }

 
  return (
    <Modal footer={null} title="用户信息修改" visible={isModalVisible} onCancel={closeModal} >
      <Form
      form={form}
        name="editUser"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        initialValues={{}}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            { required: true, message: '请输入用户名' },
            { min: 4, max: 14, message: '用户名长度在4~14个字符之间' }
          ]}
        >
          <Input />
        </Form.Item>
        
        <Form.Item
          name="role"
          label="权限"
          rules={[
            {
              required: true,
            },  
          ]}
        >
          <Select
            placeholder="分配权限"
          >
            <Option value="0">管理员</Option>
            <Option value="1">普通用户</Option>
            <Option value="2">封禁用户</Option>
          </Select>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            确定修改
          </Button>
          <Button type="default" htmlType="reset" onClick={closeModal} style={{marginLeft:'15px'}}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  )
}
